package com.android.lib.messenger

import android.app.Application
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.util.Log
import com.android.lib.messenger.utils.Const
import com.android.lib.messenger.utils.ProcessUtils

class BinderClient {

    companion object {
        lateinit var context : Application
        var clientHandler: ClientHandler = ClientHandler()
        var clientMessenger : Messenger = Messenger(clientHandler)
        var messengerConnection: ServiceConnection = MessengerConnection()
        /**
         *  服务端的 Messenger
         */
        var serverMessenger : Messenger? = null

        private fun bindMessengerService() {
            val intent = Intent(context, BinderServer::class.java)
            context.bindService(intent, messengerConnection, Context.BIND_AUTO_CREATE)
        }

    }

    /**
     * 绑定通讯池
     *
     * @param context 上下文
     */
    fun bindService(application : Application) {
        context = application
        bindMessengerService()
    }

    /**
     * 取消通讯池绑定
     *
     * @param context 上下文
     */
    fun unBind(context: Context) {
        context.unbindService(messengerConnection)
    }

    /**
     * 发送消息到服务端
     *
     * @param bundle 消息内容
     */
    fun sendMsg(bundle: Bundle?) {
        val msg: Message = Message.obtain(clientHandler, Const.SEND_MSG_TO_TARGET)
        msg.data = bundle
        msg.replyTo = clientMessenger
        serverMessenger?.send(msg)
    }

    class ClientHandler : Handler() {
        override fun handleMessage(msg: Message) {
            //客户端用ClientHandler接收并处理来自于Service的消息
            MessageProcessor.onMessageReceive(msg.data)
        }
    }

    class MessengerConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            //客户端与Service建立连接，我们可以通过从Service的onBind方法中返回的IBinder初始化一个指向Service端的Messenger
            serverMessenger = Messenger(service)
            val key: Int = ProcessUtils.getProcessName(context).hashCode()
            val subscribeMsg = Message.obtain(clientHandler, Const.SUBSCRIBE, key, 0)
            //需要将Message的replyTo设置为客户端的clientMessenger，以便Service可以通过它向客户端发送消息
            subscribeMsg.replyTo = clientMessenger
            serverMessenger?.send(subscribeMsg)
        }

        override fun onServiceDisconnected(name: ComponentName) {
            //客户端与Service失去连接
            serverMessenger = null
        }
    }


}